<template lang="html">
    <div class="login">
        <img src="../../assets/images/logo-head.png" alt="" class="logo-img">
       <el-form labelWidth="50px">
            <el-form-item label="帐号">
                <el-input v-model="name"></el-input>
            </el-form-item>
            <el-form-item label="密码" class="password">
                <el-input v-model="password" type="password"></el-input>
            </el-form-item>
            <!-- <el-form-item class="forget">
                <router-link to="/forgetPassword" class="forget-password">忘记密码?</router-link>
            </el-form-item> -->
            <br/>
            <br/>
            <el-form-item>
                <el-button type="primary" class="el-button"
                @click="loginIn"
                v-loading.fullscreen.lock="fullscreenLoading"
                element-loading-text="登录中，请稍等"
                >登 陆</el-button>
            </el-form-item>
            <!-- <el-form-item>
                <el-button type="primary" class="el-button" @click="goss">getDesKeyFromCookie</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="el-button" @click="biss">set</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="el-button" @click="test">test des(不用点)</el-button>
            </el-form-item> -->
            <!-- <el-form-item>
                <el-button type="primary" class="el-button" @click="enncrypt">enncrypt(不用点)</el-button>
            </el-form-item> -->
       </el-form>
    </div>
</template>

<script>

import axios from "axios";
import axo from "@/assets/js/axo";
import cookie from "js-cookie";

import qs from 'qs';
import JsEncrypt from 'jsencrypt/bin/jsencrypt';
import CryptoJS from 'crypto-js';

// import { reqTime, reqNo } from '@/assets/js/utils';
import utils from '@/assets/js/utils';

import {
    mapGetters,
    mapActions
} from "vuex";

export default {
    data () {
        return {
            name: process.env.userTestName?process.env.userTestName:'',
            // name: "10086",
            password: process.env.userTestPs?process.env.userTestPs:'',
            // password: "admin001",
            fullscreenLoading: false
        };
    },
    methods: {
        loginTips (code) {
            if(code){
                this.$message({
                    message: '登录成功',
                    type: 'success',
                    duration: 1000
                });
            };/* else{
                this.$message({
                    message: '登录失败',
                    type: 'error',
                    duration: 1000
                });
            } */
        },
        biss () {
            utils.setDesKeyInCookie();
        },
        goss () {
            var a = utils.getDesKeyFromCookie();
            // console.log(a);
            // utils.setRSAKeyInCookie();
            // utils.getRSAKeyFromCookie();
            // var rawStr = "123456";
            // var wordArray = CryptoJS.enc.Utf8.parse(rawStr);
            // console.log('wordArray:', wordArray.toString());
            // var base64 = CryptoJS.enc.Base64.stringify(wordArray);
            // console.log('base64Encrypt:', base64);

            // var parsedWordArray = CryptoJS.enc.Base64.parse('MTIzNDU2');
            // console.log('parsedWordArray', parsedWordArray.toString());
            // var parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8);
            // console.log('base64Decrypt = ',parsedStr);
        },
        async enncrypt () {
            /**
             * [ RSA加密 ]
             * @param {string} publicKey -- 获取到的公钥
             * @param {string} encrypted -- 加密后的字符串
             */
            let {data: {public_key: publicKey}} = await axo.post('http://193.168.1.159:8002/data/key/public');

            // let jse = new this.$jsEncrypt.JSEncrypt();
            let jse = new JsEncrypt.JSEncrypt();

            jse.setPublicKey(`-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`);
            let encrypted = jse.encrypt('Hello, world,gogooggoo');
            console.log("加密后encrypted:", encrypted);
            await axo.post('http://193.168.1.71:8002/data/key/data', {"key": encrypted});

            // 把公钥存进浏览器
            sessionStorage.setItem('encrypted', encrypted);

            // 利用私钥测试公钥加密结果
            let privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANmMBl5TN9KbZOZ8jmHaLwInndXHRB7izR81qrgosBD0AKJnyhU6qoi8UEua5787IeX3BHWbgtEXJ603rGp8/HYfK2Pd727WOt3RSLKnjiy4WVkSENzGDit5r4UOZhdc3jeztZXHztCre1r17TFeuExYA1u4ujIf9GsoIiJHS4OFAgMBAAECgYB0tI++DnrF+yM4Gt3vVLMfPs2Hn+zFfPp5obrCLOG3Vo74kSFyHhTaYdvZk3J7vmdDDS9RQGn/baKVZGaUghSU9JDG+60t4w70z1RV+bntow83sshMz4WdZtu7V0dLdvL1kN+Q62ksDzgPBMshFZ+oiENv7L8Kq9DqycNJg2h1wQJBAO4oxpw8NyF4hmCBq2jLYPAFnj2yp5tMhpVoD4khDi4iEEDw3kb8yPpMM+q2GTJbwxNuPa793VmqbFFn+guqaO0CQQDp1/aJvb/s0eVHyg/7fvPSt/1HnkXFGtH10bAg7Vj/6ZJiZ/e32kqA6FTs0k5TtG+yNjIIDczEG4zZvbr2g6n5AkAiChPxCq46i3ZxXrc4IDF3vOXUHa/VA4gM3LWzvNTBBT9beNHcRY8YL0IQXvyU9QaZxVztoP09Lp2SuRDFEBM1AkEAoo5kbcAgSQpoLo2CqrvH1zXbtguKSMiqKA4KN/mGou/FuO65P29Z116qmq5fkMSf2OzfvsWJENJuCXdhHrjMUQJAYuUkxDTN5KSmOf+jAe+FqPZxnxZBAZdvTy1XZL/hdB4Xc6JvB15uAAmwLNu6dokS6JmSN3u791qrQCcjlFGxHw==";
            jse.setPrivateKey(`-----BEGIN PUBLIC KEY-----\n${privateKey}\n-----END PUBLIC KEY-----`);
            let decrypted = jse.decrypt(encrypted);
            console.log("解密decrypted:", decrypted);
        },
        test00 () {

        },
        async test () {
            /**
             * 参考手册：https://blog.zhengxianjun.com/2015/05/javascript-crypto-js/
             * http://qefee.com/2016/02/25/CryptoJS%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/
             *
             * DES加解密
             * @type {Object}
             */
            let reqData = {
                tokenId: "",
                body: {
                    name: "10086",
                    password: "admin001"
                }
            };

            // let md5 = CryptoJS.MD5('123456');
            // console.log("MD5:", md5.toString());

            // 获取des对称加密公钥
            // {"des_key":"DE76E3EC39801CEEE0440025"}
            // let {data: {des_key: desKey}} = await axo.post('http://193.168.1.159:8002');
            let desKey = "3C6261D7B9B6E3BCF647F647";
            // console.log("desKey:", desKey);

            // 序列化参数对象
            let cipStr = JSON.stringify(reqData);
            console.log('cipStr:', cipStr);

            // 0. DES对称加密明文
            var keyHex = CryptoJS.enc.Utf8.parse(desKey);
            var desEncrypted = CryptoJS.TripleDES.encrypt(cipStr, keyHex, {
                iv: CryptoJS.enc.Utf8.parse(keyHex),
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
                // mode: CryptoJS.mode.CBC,
                // padding: CryptoJS.pad.Pkcs7
            });
            // console.log(encrypted);
            let desEncryptedStr = desEncrypted.toString();
            console.log('加密后desEncryptedStr:', desEncryptedStr);

            // var keyHex = CryptoJS.enc.Utf8.parse(desKey);
            var desDecrypted = CryptoJS.TripleDES.decrypt(desEncryptedStr, keyHex, {
                iv: CryptoJS.enc.Utf8.parse(keyHex),
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            var desDecryptedStr = CryptoJS.enc.Utf8.stringify(desDecrypted);
            console.log('解密后desDecryptedStr:', desDecryptedStr);

            // 1. 对ciphertext密文进行md5摘要
            let cipMd5 = CryptoJS.MD5(desEncryptedStr);
            let cipMd5Str = cipMd5.toString();
            console.log("密文MD5cipMd5Str:", cipMd5Str);

            // 2. 使用服务端的公钥对md5摘要进行加密,得到密文的签名（签名-sign）
            let RSAPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHSmGkXWyU6EHbBQ1+R4M/6Yyo0Ojir/iUutHCrhzHGHkS2OIN4Gys36AdItdB8z051qujLCni6UpjRzCjPkRWg7VDA2/MyNo6brHfIQs+JTHCgdPmvXZkg0oleADOMsQzIVnk6kZfXUVCKYxAK6/6i/0Kt7LjOcMEo3EWuPV2kQIDAQAB";
            // console.log(`-----BEGIN PUBLIC KEY-----\n${RSAPublicKey}\n-----END PUBLIC KEY-----`);
            let jse = new JsEncrypt.JSEncrypt();
            // jse.setPublicKey(`-----BEGIN PUBLIC KEY-----${RSAPublicKey}-----END PUBLIC KEY-----`);
            //
            jse.setPublicKey(RSAPublicKey);
            let RSAEncrypted = jse.encrypt(cipMd5Str);

            console.log("RSA加密后encrypted:", RSAEncrypted);

            // 测试RSA解密
            let privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIdKYaRdbJToQdsFDX5Hgz/pjKjQ6OKv+JS60cKuHMcYeRLY4g3gbKzfoB0i10HzPTnWq6MsKeLpSmNHMKM+RFaDtUMDb8zI2jpusd8hCz4lMcKB0+a9dmSDSiV4AM4yxDMhWeTqRl9dRUIpjEArr/qL/Qq3suM5wwSjcRa49XaRAgMBAAECgYBkv3tfD0Ng0GTaWTTnKRIQcjeRL6F9zlVrTIQQWeCMUyk2Y9RTSSEky5NMnzl1n1Gk1LwUUzsOA3Sl4cnShvgT6xutrd03cQXIxzct4FYGGHiMdDhI2dcKNKU4e3M+H9KB7OZGCaBPp4FS+bZebxxeRJhDKsfn/Oajsbcz4VxhUQJBAOAomb4DZfJXfI0Pu6Si9TIxyZNdZZTbFJ5oR2WAAYGYWFmgBcDnYPv/bvd2iVtjQnBy/M6fc45Ci6nepalEOvMCQQCagiUpQCThT1j+xwTgPV0/IRkSW+o0KxRpfabtqQ45MY1xraUVkqT0xTFozGxyM8O0nB75R19yWrkX+wcpqqFrAkEA3cLM9tLd1LcAnX1nIiWldhcTWRsZF/71kxGPMLdGxjM1lNVfW8yMgkHeQiufEC5O2Hip6rCM3byv90oxkhfSSQJAAweMPPvR/Uz1/MDgOplZa7R1bmO4+t7hXpQlIsHO0pZDJLh35S1j6Jy5NEnV0oNrUe5BuTeKCo721B6K7Gk5EwJACVXF++arUY1ErYIDDMmMv6mQW+ikXY4PaLZvBjTcRNMBOmYdgN9EnI+ayj6VBCAYOn0UVddWd1d4m2Z8Xiuysg==";
            // jse.setPrivateKey(`-----BEGIN RSA PRIVATE KEY-----\n${privateKey}\n-----END RSA PRIVATE KEY-----`);

            let desJse = new JsEncrypt.JSEncrypt();
            desJse.setPrivateKey(privateKey);
            let RSADecrypted = desJse.decrypt(RSAEncrypted);
            console.log("RSA解密decrypted:", RSADecrypted);

            let ins = axios.create({
                baseURL: 'http://193.168.1.171:18002'
                // baseURL: 'http://193.168.1.42:18002'
            });
            ins.post('/api-sys/user/login', {
                "reqNo": utils.reqNo(),
                "reqTime": utils.reqTime(),
                "platformNo": "1",
                "channel": "0",
                "sign": RSAEncrypted,
                "ciphertext": desEncryptedStr
            }).then((res) => {
                // var keyHex = CryptoJS.enc.Utf8.parse(desKey);
                var ciphertext = CryptoJS.TripleDES.decrypt(res.data.ciphertext, keyHex, {
                    iv: CryptoJS.enc.Utf8.parse(keyHex),
                    mode: CryptoJS.mode.ECB,
                    padding: CryptoJS.pad.Pkcs7
                });
                ciphertext = CryptoJS.enc.Utf8.stringify(ciphertext);
                console.log('解密后ciphertext:', ciphertext);
                console.log(res);
            });
        },
        loginIn () {
            this.fullscreenLoading = true;
            // this.$store.commit("getMsg", "nice to meet you.");
            // this.showMsg("hello,world");
            axo.post("/api-sys/user/login", {
                "tokenId": "",
                "body": {
                    "phone": this.name,
                    "password": this.password
                }
            }).then((res) => {
                console.log(res);
                this.fullscreenLoading = false;
                let state = res.data.state;
                let ciphertext = JSON.parse(res.data.ciphertext);
                // console.log("ciphertext", ciphertext);
                if(state.code === "200" && state.message === "success"){
                    /**
                     * 混淆编码成base64
                     * @param  {[type]} rawStr [编码字符串]
                     * @return {[type]}        [编码结果]
                     */
                    let to64 = function(rawStr) {
                        var wordArray = CryptoJS.enc.Utf8.parse(rawStr);
                        // console.log('wordArray:', wordArray.toString());
                        var base64 = CryptoJS.enc.Base64.stringify(wordArray);
                        // console.log('base64Encrypt:', base64);
                        return base64;
                    };

                    // 用户信息
                    let sysUser = ciphertext.sysUser;
                    sessionStorage.setItem('sysUser', JSON.stringify(sysUser));

                    // 保存用户userNo在cookie
                    cookie.set('uNo', sysUser.userNo, { expires: 1 });

                    // 登录返回的用户信息保存到Vuex
                    // 用户权限列表
                    this.keepUserAuth(ciphertext.list);
                    sessionStorage.setItem('list', JSON.stringify(ciphertext.list));

                    // 用户信息
                    this.keepSysUser(ciphertext.sysUser);
                    cookie.set('sysUser', ciphertext.sysUser, { expires: 1 });

                    this.keepTokenId(ciphertext.tokenId);
                    // 登录后的token保存在cookie，加了字符串混淆
                    let tokenId = ciphertext.tokenId;
                    // cookie.set('tokenId', tokenId, { expires: 1 });
                    cookie.set('a1To', to64(tokenId.slice(0, 10)), { expires: 1 });
                    cookie.set('ncs', to64(tokenId.slice(10, 20)), { expires: 1 });
                    cookie.set('idTo3', to64(tokenId.slice(20)), { expires: 1 });

                    this.loginState(true);

                    // 提示
                    this.loginTips(true);

                    // 跳转到管理首页
                    this.$router.replace({path: this.$route.query.redirect?this.$route.query.redirect : "/"});
                }else{
                    this.loginTips(false);
                }
            }).catch((error) => {
                this.fullscreenLoading = false;
                console.log(error);
            });
            // console.log(this.$route);
        },
        ...mapActions([ // 加载需要用到在actions绑定的方法
            "showMsg",
            "loginState",
            "getRSAPublicKey",
            "getDESPublicKey",
            "keepUserAuth",
            "keepSysUser",
            "keepTokenId"
        ])
    },
    computed: {
        ...mapGetters([ // 加载从getters上绑定的状态值
            "msg",
            "isLogin",
            "RSAPublicKey",
            "DESPublicKey"
        ])
    },
    mounted () {
        // this.getRSAPublicKey();
        // this.getDESPublicKey();
    }
};
</script>

<style lang="scss" scoped>
    .login{
        width: 100%;
        height: 100%;
        overflow: hidden;
        .logo-img{
            display: block;
            margin:200px auto 20px;
            width: 120px;
        }
        .el-form{
            width: 300px;
            height: auto;
            margin:0 auto;
            padding-right: 50px;
            .password{
                margin-bottom: 0;
            }
            .forget{
                margin: 0;
                .forget-password{
                    float: right;
                    color: #1d90e6;
                    font-size:12px;
                }
            }
            .el-form-item{
                .el-button{
                    width: 250px;
                }
            }
        }
    }
</style>
